const mongoose = require('mongoose');

const permissionSchema = mongoose.Schema(
  {
    module: {
      type: String,
      required: true,
      trim: true,
    },
    actions: {
      type: [String],
      required: true,
      default: [],
    },
  },
  {
    _id: false,
  }
);

const roleSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    description: {
      type: String,
      trim: true,
      default: '',
    },
    permissions: {
      type: [permissionSchema],
      default: [],
    },
    isDeleted: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

/**
 * 检查角色名是否已被使用
 * @param {string} name - 角色名
 * @param {ObjectId} [excludeRoleId] - 排除的角色ID
 * @returns {Promise<boolean>}
 */
roleSchema.statics.isNameTaken = async function (name, excludeRoleId) {
  const role = await this.findOne({ name, _id: { $ne: excludeRoleId }, isDeleted: false });
  return !!role;
};

/**
 * 检查角色是否有指定权限
 * @param {string} module - 模块名称
 * @param {string} action - 操作类型
 * @returns {boolean}
 */
roleSchema.methods.hasPermission = function (module, action) {
  const role = this;
  const modulePermission = role.permissions.find((p) => p.module === module);
  if (!modulePermission) return false;
  return modulePermission.actions.includes(action) || modulePermission.actions.includes('all');
};

/**
 * @typedef Role
 */
const Role = mongoose.model('Role', roleSchema, 'roles');

module.exports = Role;